package util

/**
* @author aFun
* @data 2025/4/10 01:04
* @email: afunaaa222@163.com / 1030935903
* @address: Guangdong University of Technology, China
 */

import (
	"math/rand"
	"sort"
)

// golang的map是无序的，因此每次遍历map都会出现不同的顺序
func Random_by_weight(weightPro map[string]int) string {
	// ["up_1":800, "up_2":195, "up_3":5]
	keys := make([]string, len(weightPro))
	for key := range weightPro {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	var weightedSum int = 0
	for _, weight := range weightPro {
		weightedSum += weight
	}
	randomWeight := rand.Intn(weightedSum)
	curSum := 0

	for _, key := range keys {
		curSum += weightPro[key]
		if randomWeight < curSum {
			return key
		}
	}
	panic("error!")
}
